package ch.doublet.jw.pubdownloader;

import java.io.File;

public class DownloadWatchtower {

	final static String DOWNLOAD_DIRECTORY = "D://temp/jw-publication/";
	private final static String BASE_URL = "http://www.jw.org/apps/X_TRGCHlZRQVNYVrXF?fileformat=";

	public static void main(String[] args) {

		String[] langArray = new String[] { "X", "E", "I" };
		String[] pubArray = new String[] { "g", "w" };
		String[] typeArray = new String[] { "pdf", "epub" };

		int fromYear = 2012;
		int toYear = 2013;

		for (int year = fromYear; year <= toYear; year++) {
			// every months
			for (int month = 1; month <= 12; month++) {
				// every language
				for (String lang : langArray) {
					// every fileformat
					for (String type : typeArray) {
						// every publicationtype
						for (String pub : pubArray) {
							downloadFile(new Publication(lang, pub, type,
									month, year));
						}
					}
				}
			}
		}

	}

	private static void downloadFile(Publication parameterObject) {

		String url = getUrl(parameterObject);
		String destinationDir = getTargetDirectory(parameterObject);

		File file = handleFile(parameterObject, destinationDir);

		if (!file.exists()) {
			UrlDownloaderHelper.fileDownload(url, destinationDir,
					parameterObject.getFileName());
		} else {
			System.out.println("File already exists: " + file.getName());
		}

		delteEmtpyFile(file);

	}

	private static File handleFile(Publication parameterObject,
			String destinationDir) {
		String filepath = destinationDir + parameterObject.getFileName();

		new File(destinationDir).mkdir();

		File file = new File(filepath);
		delteEmtpyFile(file);
		return file;
	}

	private static String getTargetDirectory(Publication publication) {
		return String.format(DOWNLOAD_DIRECTORY + "%s/%s/%s/",
				publication.getLang(), publication.getPub(),
				publication.getType());
	}

	private static String getUrl(Publication parameterObject) {
		final String type = parameterObject.getType().toUpperCase();
		String base = BASE_URL + type + "&issue=" + parameterObject.getDate()
				+ "&output=html&pub=" + parameterObject.getPub()
				+ "&langwritten=" + parameterObject.getLang();
		return base;
	}

	private static void delteEmtpyFile(File file) {
		if (file.exists() && file.length() < 5000) {
			file.delete();
			System.out.println("Delete File: " + file.getName());
		}
	}
}
